<template>
  <md-nav-bar
    title="会员"
    :bgInfo="{
      type: 'colorBg',
      height: '384rpx',
      backgroundColor: 'linear-gradient(154deg, #A7E4D1 0%, #F4FFFC 100%)',
    }" />
  <!-- 顶部渐变背景 -->
  <view class="vip-header">
    <image class="avatar" :src="data.userinfo?.avatar" mode="aspectFill" />
    <view class="user-info">
      <view class="user-name">{{ data.userinfo?.nickname }}</view>
      <view class="user-adou">
        <image class="adou-icon" src="https://cdn.xmxiaomai.com/isong_static/my/Group%203.png" mode="widthFix"></image>
        <text class="adou-num">{{ data.adou }}</text>
        <text class="adou-label">A豆</text>
        <md-agreement text="A豆说明" isIcon />
      </view>
    </view>
    <view class="user-vip">{{ data.userinfo?.level?.name }}</view>
  </view>
  <view class="vip-container">
    <!-- 充值卡片 -->
    <view class="vip-card">
      <view class="vip-card-title">充值礼包</view>
      <view class="vip-card-link" @click="onRecord">充值记录</view>
      <view class="vip-levels">
        <view
          v-for="(item, idx) in vipList"
          :key="idx"
          :class="['level-item', idx === data.index ? 'active' : '']"
          @click="() => handlePay(idx, item)">
          <view class="level-title">{{ item?.packageName }}</view>
          <view class="level-price">
            <text class="level-unit">￥</text>{{ formatUnitCentToYuan(item.price) }}
          </view>
          <view class="level-desc">
            <text class="level-desc-text">获得</text>
<!--            <image-->
<!--              class="adou-icon"-->
<!--              src="https://cdn.xmxiaomai.com/isong_static/my/Group%203.png"-->
<!--              mode="widthFix"></image>-->
            <text class="adou-num">{{ item?.bonusPoints }}&nbsp;A豆</text>
          </view>
        </view>
      </view>
      <view class="custom-label">自定义金额</view>
      <input
        class="custom-input"
        type="number"
        v-model="customAmount"
        @focus="customFocus"
        placeholder="请输入正整数金额" />
      <view class="rate-tip">1元 = {{ data.config?.pricePointNum || 10 }}A豆，A豆只能用于：歌曲测评、MV制作的抵扣</view>
      <button class="buy-btn"
              :class="{ 'ios-disabled': isIOS }"
              :loading="buying" :disabled="buying || isIOS" @click="onBuy" >{{ isIOS ? 'IOS暂不支持' : '立即购买' }}</button>
      <view class="vip-agree">
        <checkbox :size="12" :icon-size="12" :checked="checked" @click="checked = !checked" />
        <text>充值即表示阅读并同意</text>
        <md-agreement text="会员协议" />
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onLoad, onShow } from '@dcloudio/uni-app';
import {computed, reactive, ref} from 'vue';
// 接口
import api from '@/api';
import type { Common, Pay, User } from '@/api/data';
import { Toast, formatUnitCentToYuan, formatUnitYuanToCent } from '@/utils/util';

const data = reactive({
  index: 0,
  currentItem: {} as Pay.List.Data, // 当前选中的套餐信息
  adou: 0,
  userinfo: {} as User.Get.Data,
  config: {} as Common.Configuration.Data,
});

const vipList = ref<Pay.List.Data[]>([]);
const buying = ref(false);
const customAmount = ref('');
const checked = ref(false);

const isIOS = computed(() => {
  const {system} = wx.getSystemInfoSync()
  const config = uni.getStorageSync('config');
  const iosShowFlag = config?.iosShowFlag || false;
  return system.toLowerCase().includes('ios') && iosShowFlag;
});

// 选中充值套餐回调
const handlePay = (index: number, item: Pay.List.Data) => {
  data.index = index;
  data.currentItem = item;
  customAmount.value = ''; // 重置自定义金额
};

// 跳转充值记录
function onRecord() {
  uni.navigateTo({
    url: '/pages/sub/my/rechargeRecord',
  });
}

async function onBuy() {
  if (isIOS.value) {
    return;
  }
  if (!checked.value) {
    Toast('请勾选《会员协议》！');
    return;
  }
  const order = await fetchCreateOrderId();
  // 存咋订单才会继续往下走
  if (order?.payOrderId) {
    await fetchSubmit(order.payOrderId);
  }
}

// 自定义金额聚焦
const customFocus = () => {
  data.index = -1; // 取消套餐选中
  data.currentItem = {} as any;
};

/**
 * 接口相关
 */
// 获取用户信息及会员等级
const fetchGetUserinfo = async () => {
  try {
    const res = await api.User.get();
    data.userinfo = res.data;
  } catch (e) {}
};

// 获取剩余a豆数量
const fetchGetPoint = async () => {
  try {
    const res = await api.User.getPoint();
    data.adou = res.data;
  } catch (error) {}
};

// 获取套餐列表
const fetchGetList = async () => {
  try {
    const res = await api.Pay.list();
    vipList.value = res.data;
    // 默认选中第一项
    if (vipList.value.length) {
      handlePay(0, vipList.value[0]);
    }
  } catch (error) {}
};

// 创建订单
const fetchCreateOrderId = async () => {
  const _id = uni.getStorageSync('auth')?.userId;
  let _price = data.currentItem?.price;
  // 自定义金额
  if (data.index == -1) {
    const reg = /^[1-9]\d*$/;
    if (!reg.test(customAmount.value)) {
      Toast('请输入正整数的金额');
      return;
    }
    _price = +formatUnitYuanToCent(customAmount.value);
  }
  try {
    const res = await api.Pay.point({
      userId: _id,
      payPrice: _price,
      packageId: data.currentItem.packageId,
    });
    return res?.data;
  } catch (error) {}
  return undefined;
};

// 通过订单，提交支付
const fetchSubmit = async (orderId: number) => {
  const auth = uni.getStorageSync('auth');
  try {
    buying.value = true;
    const res = await api.Pay.submit({
      id: orderId,
      channelCode: 'wx_lite', // 微信支付
      channelExtras: {
        openid: auth?.openid,
      },
    });
    const payConfig = JSON.parse(res.data?.displayContent || '');
    // 线上 弹出微信支付
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: {},
      nonceStr: payConfig?.nonceStr, // 随机字符串
      package: payConfig?.packageValue, // 固定值
      signType: payConfig?.signType,
      timeStamp: payConfig?.timeStamp, // 时间戳（单位：秒）
      paySign: payConfig?.paySign, // 签名，这里用的 MD5/RSA 签名
      async success(res) {
        console.log(res);
        uni.showModal({
          title: '提示',
          content: '充值成功',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              fetchGetPoint();
            }
          },
        });
        buying.value = false;
      },
      fail(e) {
        buying.value = false;
        console.log(e);
        fetchPayCancelOrder(auth?.userId, orderId);
      },
    });
  } catch (error) {}
  return undefined;
};

const fetchPayCancelOrder = async (memberId: number, payOrderId: number) => {
  try {
    await api.Ad.payCancel({
      memberId,
      payOrderId,
    });
    Toast('订单取消');
  } catch (e) {}
};

onLoad(() => {
  data.config = uni.getStorageSync('config');
  fetchGetUserinfo();
  fetchGetPoint();
  fetchGetList();
});

onShow(() => {
  // 接收下一个页面带回来的参数
  uni.$once('userAgreement', function (data) {
    if (data?.agree) {
      checked.value = data?.agree;
    }
  });
});
</script>

<style lang="scss" scoped>
.vip-container {
  height: calc(100vh - 218rpx - 44px - 25px);
  background: #f5f8f7;
  padding-bottom: 32rpx;
}
.vip-header {
  padding: 48rpx 32rpx 32rpx 32rpx;
  display: flex;
  align-items: center;
  position: relative;
  margin-top: -218rpx;
}
.avatar {
  width: 104rpx;
  height: 104rpx;
  border-radius: 50%;
  background: #eee;
  margin-right: 24rpx;
  flex-shrink: 0;
}
.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.user-name {
  font-size: 32rpx;
  color: #222;
  font-weight: 600;
  margin-bottom: 8rpx;
}
.user-adou {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #00785a;
}
.adou-icon {
  width: 20rpx;
  height: 25rpx;
  margin-right: 4rpx;
}
.adou-num {
  font-size: 24rpx;
  font-weight: 600;
  font-weight: blod;
}
.adou-label {
  font-size: 28rpx;
  color: #2b2a2a;
  margin-left: 6rpx;
}
.user-vip {
  position: absolute;
  right: 32rpx;
  top: 48rpx;
  background: #ffe7b2;
  color: #b88a2a;
  font-size: 28rpx;
  border-radius: 32rpx;
  padding: 0 28rpx;
  height: 48rpx;
  line-height: 48rpx;
  font-weight: 500;
  box-shadow: none;
}
.vip-card {
  height: 100%;
  background: #fff;
  border-radius: 48rpx 48rpx 0 0;
  padding: 40rpx 32rpx 32rpx 32rpx;
  position: relative;
  z-index: 2;
  box-shadow: 0 4rpx 24rpx 0 #e0e0e0;
  display: flex;
  flex-direction: column;
}
.vip-card-title {
  font-size: 30rpx;
  color: #222;
  font-weight: 600;
  margin-bottom: 8rpx;
}
.vip-card-link {
  position: absolute;
  right: 32rpx;
  top: 40rpx;
  color: #00785a;
  font-size: 28rpx;
}
.vip-levels {
  display: flex;
  margin: 32rpx 0 0 0;
}
.level-item {
  flex: 1;
  background-image: url('https://cdn.xmxiaomai.com/isong_static/my/Group%208.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 216rpx;
  height: 300rpx;
  border: 3rpx solid #ffe7b2;
  border-radius: 24rpx;
  margin-right: 24rpx;
  padding: 32rpx 0 24rpx 0;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
  box-sizing: border-box;
}
.level-item:last-child {
  margin-right: 0;
}
.level-item.active {
  background-image: url('https://cdn.xmxiaomai.com/isong_static/my/Group%205.png');
  border: 4rpx solid #ffd699;
  box-shadow: 0 4rpx 16rpx 0 #ffe7b2;
}
.level-title {
  font-size: 28rpx;
  color: #2b2a2a;
  font-weight: 400;
  margin-bottom: 8rpx;
}
.level-price {
  font-size: 36rpx;
  color: #593a2e;
  font-weight: 600;
  margin-bottom: 8rpx;
}
.level-unit {
  font-size: 24rpx;
}
.level-desc-text {
  font-size: 24rpx;
  color: #2b2a2a;
  margin-right: 4rpx;
}
.level-desc {
  font-size: 26rpx;
  color: #ae6702;
  display: flex;
  align-items: center;
}
.custom-label {
  font-size: 28rpx;
  color: #222;
  margin: 40rpx 0 12rpx 0;
}
.custom-input {
  height: 72rpx;
  border: 2rpx solid #bbb;
  border-radius: 18rpx;
  font-size: 32rpx;
  color: #222;
  background: #fafafa;
  padding: 0 24rpx;
  margin-bottom: 18rpx;
}
.rate-tip {
  text-align: center;
  color: #444;
  font-size: 26rpx;
  margin: 18rpx 0 32rpx 0;
}
.buy-btn {
  width: 100%;
  height: 90rpx;
  background: #006a56;
  color: #fff;
  font-size: 36rpx;
  border-radius: 60rpx;
  font-weight: 400;
  border: none;
  margin-top: 8rpx;
  box-shadow: 0 4rpx 16rpx 0 #e0e0e0;
}
.vip-agree {
  display: flex;
  align-items: center;
  margin-top: 32rpx;
  font-size: 26rpx;
  color: #444;
  justify-content: center;
}
.vip-link {
  color: #00785a;
  margin-left: 4rpx;
}
</style>
